package hydrap2p.modulemanager;

import java.io.IOException;
import java.net.BindException;

import hydrap2p.ServiceLocation;
import hydrap2p.helper.ServiceConnector;
import hydrap2p.helper.ThriftServerThread;
import hydrap2p.proxy.manager.ProxyManager;
import hydrap2p.proxy.manager.ProxyManager.Iface;
import hydrap2p.servicemanager.NameTaken;

import org.apache.thrift.TException;

public class ProxyRegisterListener implements Runnable {

	private ModuleController controller;
	private ProxyManager.Iface proxy;
	private ServiceLocation localmodulemanager;

	public ProxyRegisterListener(ModuleController controller, Iface proxy, ServiceLocation localmodulemanager) {
		this.controller=controller;
		this.proxy = proxy;
		this.localmodulemanager = localmodulemanager;
	}
	
	@Override
	public void run() {

		try {
			proxy.setProxyServiceLocation("ModuleManager", localmodulemanager);
			
			// Register this ModuleManager to listen to the other ModuleManager
			ModuleManager.Iface realmanager=ServiceConnector.getService(ModuleManager.Client.class, proxy.getRealServiceLocation("ModuleManager"));
			ThriftServerThread proxylistener = new ThriftServerThread(new ModuleListener.Processor(new ProxyModuleListener(controller, realmanager)), null);
			proxylistener.start();
			ServiceLocation callback=proxy.openCallbackPort(proxylistener.getLocation(), proxy.getRealServiceLocation("ModuleManager"));
			boolean ret=realmanager.subscribe(callback);
			if (!ret)
				System.err.println("Could not register as a listener to ProxyManager");
			ret=false;
		} catch (NameTaken e) {
			// If there's already a ModuleManager running locally
			System.err.println("Could not register as ModuleManager with ProxyManager");
			System.exit(1);
		} catch (TException e) {
			// Random failure while talking to Thrift
			e.printStackTrace();
		} catch (BindException e) {
			// Rare, could not open a port to listen at
		} catch (IOException e) {
			// Could not communicate to Manager or open ports or several other bad things
			e.printStackTrace();
		}
	}

}
